<template>
  <div class="friendInfo" v-if="show && friendInfo">
    <div class="clearfix">
      <img
        class="friendInfo-avatar"
        :src="friendInfo.avatar"
        @click="openModal(friendInfo?.avatar!)"
        alt=""
      />
      <div class="friendInfo-property">
        <span class="friendInfo-property__remarkName">{{ friendInfo.remark }}</span>
        <span class="friendInfo-property__gender">
          <SvgIcon v-if="friendInfo.sex === '男'" icon-class="man" />
          <SvgIcon v-else icon-class="woman" />
        </span>
        <div class="friendInfo-property__more">
          <SvgIcon
            icon-class="more"
            popper-class="friendInfo-property__more--icon"
            @click="showMenu = !showMenu"
          />
          <transition v-show="showMenu" name="fade">
            <dl ref="userInfoMenuRef" class="friendInfo-menu">
              <dt @click="openSetup(0)">设置备注和标签</dt>
              <dt @click="openSetup(1)">设置朋友圈权限</dt>
            </dl></transition
          >
        </div>
        <p class="friendInfo-property__nickName">昵称：{{ friendInfo.nickName }}</p>
        <p class="friendInfo-property__age">年龄：{{ friendInfo.age }}</p>
        <p class="friendInfo-property__account">账号：{{ otherId }}</p>
        <p class="friendInfo-property__address" v-if="friendInfo.address">
          地区：{{ friendInfo.address }}
        </p>
      </div>
    </div>
    <el-divider border-style="dashed" />
    <div class="friendInfo-main">
      <div class="clearfix" v-if="friendInfo.signature">
        <span class="friendInfo-main__name">个性签名</span>
        <span class="friendInfo-main__value">{{ friendInfo.signature }}</span>
      </div>
      <div class="friendInfo-main__remark clearfix">
        <span class="friendInfo-main__name">备注名</span>
        <span class="friendInfo-main__value">{{ friendInfo.remark }}</span>
      </div>
      <div class="clearfix" v-if="friendInfo.group">
        <span class="friendInfo-main__name">分组</span>
        <span class="friendInfo-main__value">{{ friendInfo.group }}</span>
      </div>
      <div
        class="friendInfo-main__permission clearfix"
        v-if="friendInfo.disabledOtherLook || friendInfo.disabledSelfLook"
      >
        <span class="friendInfo-main__name">朋友权限</span>
        <span class="friendInfo-main__value">{{
          friendInfo.disabledOtherLook && !friendInfo.disabledSelfLook
            ? "不让对方看"
            : !friendInfo.disabledOtherLook && friendInfo.disabledSelfLook
            ? "不看对方"
            : "既不看对方也不让对方看"
        }}</span>
      </div>
    </div>
    <el-divider border-style="dashed" />
    <div class="friendInfo-dynamic" @click="showDynamic = true">个人动态</div>
    <el-divider border-style="dashed" />
    <div class="friendInfo-footer">
      <el-button
        class="friendInfo-footer__button"
        type="primary"
        :disabled="isSendLoading"
        :loading="isSendLoading"
        @click="startSend(otherId)"
        ><template #loading><Loading /></template>发消息</el-button
      >
    </div>
    <setup
      to=".chat-box"
      v-model="showSetup"
      :type="setupState"
      v-model:info-rem-group="infoRemGroup"
      v-model:info-permission="infoPermission"
      :other-id="otherId"
      width="32%"
    ></setup>
  </div>
  <template v-else
    ><feed-back
      :is-requesting="isRequesting"
      :is-error="isError"
      message="请求出错啦"
      @retry="requestInfo(otherId)"
    ></feed-back
  ></template>
  <Modal v-model="showModal"> <img class="img-browser" :src="imgSrc" alt="" /> </Modal>
  <template v-if="friendInfo"
    ><dynamic
      v-model="showDynamic"
      :usr-info="Object.assign(friendInfo, { userId: otherId })"
    ></dynamic
  ></template>
</template>

<script lang="ts" setup>
import { ref, computed, watch } from "vue";
import feedBack from "@/components/ui-components/feedBack.vue";
import { source, refreshAxios } from "@/plugins/http";
import { useFriendPinia } from "@/pinia/friend";
import { useUserPinia } from "@/pinia/user";
import { useMessagePinia } from "@/pinia/messages";
import { storeToRefs } from "pinia";
import { useRouter } from "vue-router";
import Modal from "@/components/ui-components/modal.vue";
import { ElMessage } from "element-plus";
import setup from "@/components/messages/colRight/detailMessage/setup.vue";
import dynamic from "@/components/dynamic/index.vue";

const props = defineProps<{
  otherId: string;
  initials: string;
}>();

const router = useRouter();

const friendStore = useFriendPinia();
const messageStore = useMessagePinia();
const { user } = storeToRefs(useUserPinia());
const { friends, isRequGetAllFriend, friendsInfos } = storeToRefs(friendStore);

/**
 * 对方的备注和分组
 */
const infoRemGroup = ref<{ remark: string; group: string }>({
  remark: "",
  group: "",
});
/**
 * 对对方的朋友圈权限
 */
const infoPermission = ref<Permission>({
  disabledOtherLook: false,
  disabledSelfLook: false,
});

const friendInfo = computed(() => {
  const data = friendsInfos.value.get(props.otherId);
  infoRemGroup.value.remark = data?.remark ? data.remark : "";
  infoRemGroup.value.group = data?.group ? data.group : "";
  infoPermission.value.disabledOtherLook = data?.disabledOtherLook
    ? data.disabledOtherLook
    : false;
  infoPermission.value.disabledSelfLook = data?.disabledSelfLook
    ? data.disabledSelfLook
    : false;
  return data;
});

/**
 * 是否显示好友的详情信息
 */
const show = ref<boolean>(false);
/**
 * 是否正在请求好友的详情消息
 */
const isRequesting = ref<boolean>(false);
/**
 * 请求是否出错
 */
const isError = ref<boolean>(false);

// 开始请求好友的详情消息
const requestInfo = (otherId: string) => {
  // 取消上一次请求
  if (isRequesting.value) {
    source.cancel();
    refreshAxios();
    isRequesting.value = false;
  }
  if (isError.value) isError.value = false;
  if (show.value) show.value = false;
  isRequesting.value = true;
  friendStore
    .getFriendInfos({
      otherId,
      selfId: user.value.userId,
    })
    .then((code: number) => {
      isRequesting.value = false;
      if (code === 1) {
        show.value = true;
        if (friendInfo.value?.bkImg) new Image().src = friendInfo.value.bkImg;
      } else if (code === 0) isError.value = true;
      else if (code === -2)
        // 表示对方并未是自己的好友，请求失败
        router.push("404");
    })
    .catch(() => {
      isRequesting.value = false;
      isError.value = true;
    });
};

watch(
  () => props.otherId,
  (newId: string) => {
    if (!friends.value.has(props.initials)) router.push({ name: "contact" });
    else if (isRequGetAllFriend.value) {
      // 如果请求没请求过消息记录的话
      if (!friendsInfos.value.has(newId)) requestInfo(newId);
      else if (!show.value) show.value = true;
    } else {
      const timing = setInterval(() => {
        // 如果请求消息聊天列表结束
        if (isRequGetAllFriend.value) {
          clearInterval(timing);
          if (!friendsInfos.value.has(newId)) requestInfo(newId);
        }
      }, 10);
    }
  },
  { immediate: true }
);

/**
 * 是否正在给好友发送消息
 */
const isSendLoading = ref<boolean>(false);
// 开始给好友发送消息
const startSend = (userId: string) => {
  if (messageStore.chatList.has(userId))
    router.replace({ path: "/chatRecord", query: { userId } });
  else {
    isSendLoading.value = true;
    messageStore
      .readySendMessage({
        selfId: user.value.userId,
        otherId: userId,
      })
      .then((code: number) => {
        isSendLoading.value = false;
        if (code === 1) router.replace({ path: "/chatRecord", query: { userId } });
        else if (code === -2)
          ElMessage({
            type: "error",
            message: "操作失败，对方和自己不是好友关系",
            duration: 1500,
          });
        else
          ElMessage({
            type: "error",
            message: "跳转失败",
            duration: 1500,
          });
      })
      .catch(() => {
        isSendLoading.value = false;
        ElMessage({
          type: "error",
          message: "跳转失败",
          duration: 1500,
        });
      });
  }
};

/**
 * 是否显示操作菜单
 */
const showMenu = ref<boolean>(false);
const userInfoMenuRef = ref<HTMLDListElement>();
/**
 * 判断用户所点击的元素是否符合标准
 */
const judgeClickMenu = (e: Event) => {
  const target: HTMLElement = e.target as HTMLElement;
  if (
    !userInfoMenuRef.value?.contains(target) &&
    typeof target.className === "string" &&
    !target.className?.includes("friendInfo-property__more--icon")
  )
    showMenu.value = false;
};

watch(
  () => showMenu.value,
  (newValue) => {
    if (newValue) document.addEventListener("click", judgeClickMenu);
    else document.removeEventListener("click", judgeClickMenu);
  }
);

/**
 * 是否打开设置菜单
 */
const showSetup = ref<boolean>(false);
/**
 * 设置的状态，0代表设置备注和标签，1代表设置朋友圈权限
 */
const setupState = ref<0 | 1>(0);
/**
 * 打开对好友设置对话框
 * @param type - 0代表设置备注和标签，1代表设置朋友圈权限
 */
const openSetup = (type: 0 | 1) => {
  setupState.value = type;
  showSetup.value = true;
};

/**
 * 当前用户查看的图片的url
 */
const imgSrc = ref<string>("");
/**
 * 是否显示模态框
 */
const showModal = ref<boolean>(false);
// 浏览图片时打开模态框
const openModal: (url: string) => void = (url: string): void => {
  imgSrc.value = url;
  showModal.value = true;
};

/**
 * 是否显示好友的动态
 */
const showDynamic = ref<boolean>(false);
</script>

<style lang="scss" scoped>
.fade {
  @include fade(0.15s, ease);
}

.friendInfo {
  padding: 25px 10% 0 10%;

  &-avatar {
    @include setWidHei(80px, 80px);
    border-radius: 8px;
    object-fit: cover;
    cursor: pointer;
    float: left;
  }

  &-menu {
    @include opearMenu(1001, 13px);
    top: 0;
    left: calc(100% + 6px);
    @include noselect();

    & > dt {
      padding: 5px 20px;
    }
  }

  &-property {
    float: left;
    margin-left: 5%;

    &__remark {
      font: {
        weight: 600;
        size: 17px;
      }
    }

    &__gender {
      color: #3d93ef;
      margin-left: 10px;
      font-size: 20px;
    }

    &__more {
      display: inline-block;
      position: relative;
      margin-left: 15px;

      &--icon {
        font-size: 24px;
        cursor: pointer;
      }
    }

    &__address {
      word-break: break-all;
    }

    &__nickName,
    &__account,
    &__address,
    &__age {
      margin: 4px 0 3px;
      font-size: 14px;
      color: #626161ca;
    }
  }

  &-main {
    color: #333;

    &__name {
      margin-right: 15px;
      color: rgba(128, 124, 124, 0.909);
      width: 70px;
      float: left;
    }

    &__value {
      word-break: break-all;
    }

    &__remark {
      margin: 10px 0;
    }

    &__permission {
      margin-top: 10px;
    }
  }

  &-footer {
    margin-top: 35px;
    text-align: center;

    &__button {
      @include setWidHei(50%, 35px);
    }
  }

  &-dynamic {
    text-align: center;
    cursor: pointer;
    color: #333;
    transition: color 0.3s;

    &:hover {
      color: #52a8fd;
    }
  }
}
</style>
